package com.xx.tools.service.cjb.impl;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xx.account.domain.AccountRecord;
import com.xx.account.mapper.AccountRecordMapper;
import com.xx.account.service.IAccountRecordService;
import com.xx.common.utils.DateUtils;
import com.xx.common.utils.SecurityUtils;
import com.xx.common.utils.StringUtils;
import com.xx.tools.dto.cjb.Cjb;
import com.xx.tools.mapper.CjbMapper;
import com.xx.tools.service.cjb.ICjbService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class CjbServiceImpl implements ICjbService {

    // 创建线程池（建议作为全局变量或通过Spring注入）
    private static final ExecutorService executor = Executors.newCachedThreadPool();

    @Resource
    private CjbMapper cjbMapper;

    @Resource
    private AccountRecordMapper accountRecordMapper;

    @Override
    public List<Cjb> list(Cjb cjb) {
        return cjbMapper.selectCjbList(cjb);
    }

    @Override
    public Cjb getInfo(String id) {
        return cjbMapper.getById(id);
    }

    @Override
    public int add(Cjb cjb) {

        String postUrl = "https://gbapi.eastmoney.com/content/api/Post/FundArticleContent";

        // 截取url中的字段
        String postid = "";
        // 先尝试匹配?code=后的数字
        Matcher m = Pattern.compile("code=(\\d+)").matcher(cjb.getUrl());
        if (m.find()) postid = m.group(1);

        // 再尝试匹配路径中的数字段
        m = Pattern.compile("/(\\d+)(\\?|$)").matcher(cjb.getUrl());
        if (m.find()) postid = m.group(1);

        m = Pattern.compile(",(\\d+)\\.html$").matcher(cjb.getUrl());
        if (m.find()) postid = m.group(1);

        if (StringUtils.isEmpty(postid)) {
            throw new RuntimeException("链接格式错误");
        }

        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("postid", postid);
        paramMap.put("plat", "wap");
        paramMap.put("version", "010");
        paramMap.put("product", "Fund");
        paramMap.put("deviceid", "1");

        // 设置文章标题
        try {
            HttpResponse result = HttpUtil.createPost(postUrl).form(paramMap).execute();
            String body = result.body();
            // 创建ObjectMapper实例
            ObjectMapper objectMapper = new ObjectMapper();
            // 解析JSON字符串为JsonNode
            JsonNode rootNode = objectMapper.readTree(body);
            // 先获取data节点，再获取post_title的值
            cjb.setTitle(rootNode.path("post").path("post_title").asText());
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        // 发送POST请求
        executor.submit(() -> {
            try {
                for (int i = 0; i < cjb.getCount(); i++) {
                    HttpUtil.createPost(postUrl).form(paramMap).executeAsync();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        cjb.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        cjb.setCreateBy(SecurityUtils.getUserId().toString());
        cjb.setCreateTime(DateUtils.getNowDate());


        // 订单同步到记账中
        AccountRecord accountRecord = new AccountRecord();
        accountRecord.setId(UUID.randomUUID().toString().replaceAll("-",""));
        accountRecord.setCreateTime(DateUtils.getNowDate());
        accountRecord.setName((new BigDecimal(cjb.getCount()).divide(BigDecimal.valueOf(1000))) + "k");
        accountRecord.setUrl(cjb.getUrl());
        accountRecord.setPrice(new BigDecimal("0.0017"));
        accountRecord.setCount(cjb.getCount());
        accountRecord.setBossId("e9092007d6bc4b779d87c38effefe814");
        accountRecord.setOrderTime(cjb.getCreateTime());
        accountRecord.setCreateBy("102");
        accountRecord.setIsSuccess(0);
        accountRecordMapper.insertAccountRecord(accountRecord);

        return cjbMapper.insertCjb(cjb);
    }


}


